package info.xinfu.carban.fragment;

import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import info.xinfu.carban.Event_Send_Message;
import info.xinfu.carban.ParseUrlService;
import info.xinfu.carban.R;
import info.xinfu.carban.base.BaseFragment;
import info.xinfu.carban.entity.AddObserver;
import info.xinfu.carban.entity.UserEntity;
import info.xinfu.carban.utils.Constants;
import info.xinfu.carban.utils.SPUtils;
import com.google.gson.Gson;
import com.hui.util.log.LogUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import okhttp3.Call;
import okhttp3.MediaType;

/**
 * The type Seller obser fragment.
 */
public class SellerObserFragment extends BaseFragment {
    /**
     * The M values.
     */
//存放请假类型的map
    protected float[] mValues = new float[]{25.14f, 74.86f};
    /**
     * The M values 2.
     */
    protected float[] mValues2 = new float[]{35.20f, 64.8f};
    /**
     * The Btn bottom.
     */
    @BindView(R.id.btn_bottom)
    Button btnBottom;
    /**
     * The Tv type name.
     */
    @BindView(R.id.tv_type_name)
    TextView tvTypeName;
    /**
     * The Fee url.
     */
    @BindView(R.id.fee_url)
    EditText feeUrl;
    /**
     * The Unbinder.
     */
    Unbinder unbinder;
    /**
     * The Fee shop.
     */
    @BindView(R.id.fee_shop)
    EditText feeShop;
    /**
     * The Fee good.
     */
    @BindView(R.id.fee_good)
    EditText feeGood;
    /**
     * The Sms count.
     */
    @BindView(R.id.sms_count)
    TextView smsCount;
    /**
     * The Expire date.
     */
    @BindView(R.id.expire_date)
    TextView expireDate;
    private int mYear;
    private boolean isFirstEntry = false;
    private String obserUrl = "";
    private String mDate = "";
    //当前页码
    private int pageNo = 1;
    private boolean isLastPage = false;

    private UserEntity userEntity;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    /*    mediaPlayer.stop();
        mediaPlayer = null;*/
        unbinder.unbind();
    }

    /**
     * Gets instance.
     *
     * @param type the type
     * @return the instance
     */
    public static SellerObserFragment getInstance(String type) {
        SellerObserFragment fragment1 = new SellerObserFragment();
        Bundle bdl = new Bundle();
        bdl.putString("type", type);
        fragment1.setArguments(bdl);
        return fragment1;
    }

    @Override
    protected void initListener() {

    }

    @Override
    protected void initView() {
//        getDefault().register(this);
//        feeShop.setText(SPUtils.getString("email", ""));
    }

    @Override
    protected void initData() {
        String uname = SPUtils.getString(Constants.username, "");
        getUserdata(uname);
    }

    @Override
    protected int getRootViewId() {
        return R.layout.fragment_seller_obser;
    }


    /**
     * Sen text mail.
     */
    public void senTextMail() {
//        SendMailUtil.send(feeShop.getText().toString(), "宝贝下架通知", "此宝贝已下架，链接地址为" + obserUrl);
    }

    /**
     * On click.
     *
     * @param view the view
     */
    @OnClick({R.id.btn_bottom})
    void onClick(View view) {
        switch (view.getId()) {

            case R.id.btn_bottom:
                //跳到新建页面
                obserUrl = feeUrl.getText().toString();
                if (TextUtils.isEmpty(obserUrl)) {
                    showToast("信息不完整");
                } else {

//                    SPUtils.putString("url", feeUrl.getText().toString());
//                    SPUtils.putString("email", feeShop.getText().toString());
                    connectNetToSubmit();
                }

//                startLocationAlarm();
//                btnBottom.setText("结束监控");
                break;
            default:

                break;
        }
    }

    private AlarmManager alarmManager;
    private Intent collectIntent;
    private PendingIntent collectSender;

    private void startLocationAlarm() {

        alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        collectIntent = new Intent(context, ParseUrlService.class);
        collectSender
                = PendingIntent.getService(context, 0, collectIntent, 0);
        alarmManager.cancel(collectSender);
        alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME
                , SystemClock.elapsedRealtime()
                , 10 * 1000
                , collectSender);
    }

    private void cancelAlarm() {
        alarmManager.cancel(collectSender);
    }

    private void parseJsonString(String response) {

        JSONObject jsonObject = JSON.parseObject(response);
        String resCode = jsonObject.getString("resCode");
        String resMsg = jsonObject.getString("resMsg");
        // SellerObserver
    }

    /**
     * Show alert.
     */
    protected void showAlert() {
        new AlertDialog.Builder(context).setTitle("提示：")
                .setMessage("有商品下架,具体信息已发送邮箱")
                .setCancelable(false)
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mediaPlayer.stop();
                        dialog.dismiss();
                    }
                }).setPositiveButton("知道了", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mediaPlayer.stop();
                dialog.dismiss();

            }
        }).show();


    }

    /**
     * 联网提交
     */
    private void connectNetToSubmit() {
        /**
         * 字段{userId:,postId:}
         * post json 方式
         */
        AddObserver write_post = new AddObserver();

        String uname = SPUtils.getString(Constants.username, "");
        write_post.setAvatarUrl(obserUrl);
        write_post.setUserId(uname);
        write_post.setField1(feeShop.getText().toString());
        write_post.setField2(feeGood.getText().toString());

        OkHttpUtils.postString().url(Constants.addObserver)
                .content(new Gson().toJson(write_post))
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        //结束时别忘了hideDialog（）;
                        hidePDialog();
                        showToast(e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        //结束时别忘了hideDialog;
                        hidePDialog();
                        LogUtils.e(response);
                        if (!TextUtils.isEmpty(response) && isGoodJson(response)) {
                            JSONObject jsonObject = JSON.parseObject(response);
                            String errorFlag = jsonObject.getString("errorFlag");
                            if (!errorFlag.equals("-1")) {
                                //success
                                showToast("添加成功");
                                EventBus.getDefault().post(new Event_Send_Message(true));

                            } else {
                                //error
                                showToast("该监控连接已存在~");
                            }
                        } else {
                            //error
                            showToast("添加失败~");
                        }
                    }
                });

    }

    /**
     * okhttp
     */
    private void getUserdata(String id) {
        OkHttpUtils.post().url(Constants.getuserinfo)
                .addParams("userId", id)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        //结束时别忘了hideDialog（）;
                        hidePDialog();
                        showToast(e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        //结束时别忘了hideDialog;
                        hidePDialog();
                        LogUtils.e(response);
                        if (!TextUtils.isEmpty(response) && isGoodJson(response)) {
                            userEntity = JSON.parseObject(response, UserEntity.class);
                            smsCount.setText(String.valueOf(userEntity.getTotalMoney()) + "条");
                            expireDate.setText(TimeStamp2Date(userEntity.getExpiryDate(),"yyyy年MM月dd日"));
                            showToast("成功");
//                                  getData();
                        } else {
                            //error
                            showToast("失败~");
                        }
                    }
                });

    }

    /**
     * Time stamp 2 date string.
     *
     * @param timestamp the timestamp
     * @param formats   the formats
     * @return the string
     */
    public String TimeStamp2Date(Long timestamp, String formats){
//        Long timestamp = Long.parseLong(timestampString)*1000;
        String date = new java.text.SimpleDateFormat(formats).format(new java.util.Date(timestamp));
        return date;
    }
    private void setData() {

    }

    private MediaPlayer mediaPlayer;

    /**
     * 打开raw目录下的音乐mp3文件
     */
    private void openRawMusicS() {
        mediaPlayer = MediaPlayer.create(context, R.raw.tips);
        //用prepare方法，会报错误java.lang.IllegalStateExceptio
        //mediaPlayer1.prepare();
        mediaPlayer.start();
    }


}
